package com.dmz.auth.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import com.dmz.auth.exception.CustomWebResponseExceptionTranslator;
import com.dmz.auth.granter.PhoneAndPasswordTokenGranter;
import com.dmz.auth.model.AuthUserDetails;
import com.dmz.auth.service.impl.ClientDetailsServiceImpl;
import com.dmz.auth.service.impl.UserInfoServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;

/**
 * 配置认证服务文件
 */
@Configuration
@EnableAuthorizationServer
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {

	@Autowired
	private AuthenticationManager authenticationManager;
	
	@Bean
    public UserDetailsService userDetailsService(){
        return new UserInfoServiceImpl();
    }
	
	@Bean
	public ClientDetailsService clientDetailsService() {
		return new ClientDetailsServiceImpl();
	}
	
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    	//使用自定义的ClientDetailsService
        clients.withClientDetails(clientDetailsService());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("isAuthenticated()")
                .checkTokenAccess("permitAll()");
    }

@Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		 // 配置token的数据源、自定义的tokenServices等信息,配置身份认证器，配置认证方式，TokenStore，TokenGranter，OAuth2RequestFactory
        endpoints
        		.authenticationManager(authenticationManager)
                .tokenEnhancer(tokenEnhancerChain())
                .tokenGranter(tokenGranter(endpoints))
                .exceptionTranslator(customExceptionTranslator());;
    }

	/**
	 * 配置自定义的granter,手机号验证码登陆
	 *
	 * @param endpoints
	 * @return
	 * @auth joe_chen
	 */
	public TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {
	    List<TokenGranter> granters = Lists.newArrayList(endpoints.getTokenGranter());
	    granters.add(new PhoneAndPasswordTokenGranter(
	            authenticationManager,
	            endpoints.getTokenServices(),
	            endpoints.getClientDetailsService(),
	            endpoints.getOAuth2RequestFactory()));
	    return new CompositeTokenGranter(granters);
	}
	
	 /**
     * token的持久化
     *
     * @return JwtTokenStore
     */
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    /**
     * 自定义token
     *
     * @return tokenEnhancerChain
     */
    @Bean
    public TokenEnhancerChain tokenEnhancerChain() {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new JWTokenEnhancer(), accessTokenConverter()));
        return tokenEnhancerChain;
    }

    /**
     * jwt token的生成配置
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("123456");
        return converter;
    }
    /**
     * 自定义OAuth2异常处理
     *
     * @return CustomWebResponseExceptionTranslator
     */
    @Bean
    public WebResponseExceptionTranslator<OAuth2Exception> customExceptionTranslator() {
        return new CustomWebResponseExceptionTranslator();
    }
}